package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.domain.SysRole;
import org.example.model.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "系统角色接口管理")
@RequestMapping("/sys/role")
@RestController
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;


    @ApiOperation("查询系统所有角色")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public Result<List<SysRole>> loadSysRoleList() {

        List<SysRole> sysRoleList = sysRoleService.querySysRoleList();
        return Result.success(sysRoleList);

    }

    @ApiOperation("多条件分页查询角色列表")
    @GetMapping("page")
    @PreAuthorize("hasAuthority('sys:role:page')")
    public Result<Page<SysRole>> LoadSysRolePage(@RequestParam Long current,
                                                 @RequestParam Long size,
                                                 @RequestParam(required = false) String roleName) {
        Page<SysRole> page = new Page<>(current, size);
        // 多条件分页查询角色列表
        page = sysRoleService.page(page, new LambdaQueryWrapper<SysRole>()
                .like(StringUtils.hasText(roleName), SysRole::getRoleName, roleName)
                .orderByDesc(SysRole::getCreateTime)
        );

        return Result.success(page);
    }

    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:role:save')")
    public Result<String> saveSysRole(@RequestBody SysRole sysRole){

        Boolean saved = sysRoleService.saveSysRole(sysRole);
        return Result.handle(saved);
    }

    @ApiOperation("根据标识查询角色详情")
    @GetMapping("info/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:info')")
    public Result<SysRole> loadSysRoleInfo(@PathVariable Long roleId) {
        SysRole sysRole = sysRoleService.querySysRoleInfoByRoleId(roleId);
        return Result.success( sysRole);
    }

    @ApiOperation("修改角色信息")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result<String> modifySysRole(@RequestBody SysRole sysRole) {
        Boolean updated = sysRoleService.modifySysRole(sysRole);
        return Result.handle(updated);
    }

    @ApiOperation("删除角色")
    @DeleteMapping
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public Result<String> deleteSysRole(@RequestBody List<Long> roleIdList) {
        Boolean deleted = sysRoleService.removeById(roleIdList);
        return Result.handle(deleted);
    }

}
